package com.project.web.wechat.controller.app.cpWeChat;

import com.project.common.core.utils.exception.CustomException;
import com.project.common.core.utils.exception.Result;
import com.project.web.config.WxCorp.WxCpConfig;
import com.project.web.config.WxCorp.WxCpConfiguration;
import com.project.web.wechat.controller.common.BaseController;
import com.project.web.wechat.model.app.vo.WxCpExternalContactRemarkVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.bean.WxCpTag;
import me.chanjar.weixin.cp.bean.external.*;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 外部联系人管理接口
 *
 * @author wyy
 * @date 2020-06-24
 */
@Api(tags = "外部联系人管理接口")
@RestController("workWxContactController")
@RequestMapping("/weChat/auth/workWx/contact")
public class WorkWxContactController extends BaseController {


    /**
     * 获取客户列表
     *
     * @param userId 用户ID
     * @return
     */
    @ApiOperation("获取客户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", value = "用户ID", required = true, dataType = "String"),
    })
    @GetMapping(value = "/listExternalContacts")
    public Result<List<String>> listExternalContacts(String userId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            List<String> userIds = contactService.listExternalContacts(userId);
            return getResult(userIds);
        } catch (WxErrorException e) {
            log.error("获取外部联系人列表出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取客户详情
     *
     * @param userId 用户ID
     * @return
     */
    @ApiOperation("获取客户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", value = "用户ID", required = true, dataType = "String"),
    })
    @GetMapping(value = "/getExternalContact")
    public Result<WxCpExternalContactInfo> getExternalContact(String userId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpExternalContactInfo externalContact = contactService.getExternalContact(userId);
            return getResult(externalContact);
        } catch (WxErrorException e) {
            log.error("获取外部联系人列表出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 修改客户备注信息
     *
     * @return
     */
    @ApiOperation("修改客户备注信息")
    @PostMapping(value = "/remark")
    public Result<String> remark(@RequestBody WxCpUpdateRemarkRequest wxCpUpdateRemarkRequest, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            contactService.updateRemark(wxCpUpdateRemarkRequest);
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("修改客户备注信息出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取配置了客户联系功能的成员列表
     *
     * @return
     */
    @ApiOperation("获取配置了客户联系功能的成员列表")
    @GetMapping(value = "/listFollowUser")
    public Result<List<String>> listFollowUser(HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            List<String> userIds = contactService.listFollowers();
            return getResult(userIds);
        } catch (WxErrorException e) {
            log.error("获取配置了客户联系功能的成员列表出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 配置客户联系「联系我」方式
     *
     * @return
     */
    @ApiOperation("配置客户联系「联系我」方式")
    @PostMapping(value = "/addContactWay")
    public Result<WxCpContactWayResult> addContactWay(@RequestBody WxCpContactWayInfo wxCpContactWayInfo, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpContactWayResult wxCpContactWayResult = contactService.addContactWay(wxCpContactWayInfo);
            return getResult(wxCpContactWayResult);
        } catch (WxErrorException e) {
            log.error("配置客户联系「联系我」方式出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取企业已配置的「联系我」方式
     *
     * @return
     */
    @ApiOperation("获取企业已配置的「联系我」方式")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "configId", value = "联系方式的配置id", required = true, dataType = "String"),
    })
    @GetMapping(value = "/getContactWay")
    public Result<WxCpContactWayInfo> getContactWay(String configId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpContactWayInfo contactWay = contactService.getContactWay(configId);
            return getResult(contactWay);
        } catch (WxErrorException e) {
            log.error("获取企业已配置的「联系我」方式出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 更新企业已配置的「联系我」方式
     *
     * @return
     */
    @ApiOperation("更新企业已配置的「联系我」方式")
    @PostMapping(value = "/updateContactWay")
    public Result<WxCpBaseResp> updateContactWay(@RequestBody WxCpContactWayInfo wxCpContactWayInfo, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpBaseResp wxCpBaseResp = contactService.updateContactWay(wxCpContactWayInfo);
            return getResult(wxCpBaseResp);
        } catch (WxErrorException e) {
            log.error("更新企业已配置的「联系我」方式出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }


    /**
     * 删除企业已配置的「联系我」方式
     *
     * @return
     */
    @ApiOperation("删除企业已配置的「联系我」方式")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "configId", value = "联系方式的配置id", required = true, dataType = "String"),
    })
    @GetMapping(value = "/delContactWay")
    public Result<WxCpBaseResp> delContactWay(String configId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpBaseResp wxCpBaseResp = contactService.deleteContactWay(configId);
            return getResult(wxCpBaseResp);
        } catch (WxErrorException e) {
            log.error("删除企业已配置的「联系我」方式出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取离职成员的客户列表
     *
     * @return
     */
    @ApiOperation("获取离职成员的客户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageId", value = "分页查询，要查询页号，从0开始", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每次返回的最大记录数，最大值为1000", required = true, dataType = "String")
    })
    @GetMapping(value = "/getUnassignedList")
    public Result<WxCpUserExternalUnassignList> getUnassignedList(Integer pageId, Integer pageSize, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpUserExternalUnassignList wxCpUserExternalUnassignList = contactService.listUnassignedList(pageId, pageSize);
            return getResult(wxCpUserExternalUnassignList);
        } catch (WxErrorException e) {
            log.error("获取离职成员的客户列表出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 分配离职成员的客户群
     *
     * @return
     */
    @ApiOperation("分配离职成员的客户群")
    @PostMapping(value = "/transfer")
    public Result<String> transfer(String externalUserId, String handOverUserId, String takeOverUserId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpBaseResp wxCpBaseResp = contactService.transferExternalContact(externalUserId, handOverUserId, takeOverUserId);
            return getResult(wxCpBaseResp);
        } catch (WxErrorException e) {
            log.error("离职成员的外部联系人再分配出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取企业标签库
     *
     * @return
     */
    @ApiOperation("获取企业标签库")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tagId", value = "要查询的标签id，如果不填则获取该企业的所有客户标签，目前暂不支持标签组id", required = true, dataType = "String")
    })
    @GetMapping(value = "/getCorpTagList")
    public Result<WxCpUserExternalTagGroupList> getCorpTagList(String[] tagId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpUserExternalTagGroupList corpTagList = contactService.getCorpTagList(tagId);
            return getResult(corpTagList);
        } catch (WxErrorException e) {
            log.error("获取企业标签库出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 添加企业客户标签
     *
     * @return
     */
    @ApiOperation("添加企业客户标签")
    @PostMapping(value = "/addCorpTag")
    public Result<WxCpUserExternalTagGroupInfo> addCorpTag(@RequestBody WxCpUserExternalTagGroupInfo wxCpTagGroup, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpUserExternalTagGroupInfo wxCpUserExternalTagGroupInfo = contactService.addCorpTag(wxCpTagGroup);
            return getResult(wxCpUserExternalTagGroupInfo);
        } catch (WxErrorException e) {
            log.error("添加企业客户标签出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 编辑企业客户标签
     *
     * @return
     */
    @ApiOperation("编辑企业客户标签")
    @PostMapping(value = "/editCorpTag")
    public Result<String> editCorpTag(@RequestBody WxCpTag wxCpTag, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpBaseResp wxCpBaseResp = contactService.editCorpTag(wxCpTag.getId(), wxCpTag.getName(), 1);
            return getResult(wxCpBaseResp);
        } catch (WxErrorException e) {
            log.error("编辑企业客户标签出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 删除企业客户标签
     *
     * @return
     */
    @ApiOperation("删除企业客户标签")
    @PostMapping(value = "/delCorpTag")
    public Result<WxCpBaseResp> delCorpTag(String[] tagId, String[] groupId, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpBaseResp wxCpBaseResp = contactService.delCorpTag(tagId, groupId);
            return getResult(wxCpBaseResp);
        } catch (WxErrorException e) {
            log.error("删除企业客户标签出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 编辑客户企业标签
     *
     * @return
     */
    @ApiOperation("编辑客户企业标签")
    @PostMapping(value = "/markTag")
    public Result<WxCpBaseResp> markTag(@RequestBody WxCpExternalContactRemarkVo wxCpExternalContactRemarkVo, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpBaseResp wxCpBaseResp = contactService.markTag(wxCpExternalContactRemarkVo.getUserId(), wxCpExternalContactRemarkVo.getExternalUserId()
                    , wxCpExternalContactRemarkVo.getAddTag(), wxCpExternalContactRemarkVo.getRemoveTag());
            return getResult(wxCpBaseResp);
        } catch (WxErrorException e) {
            log.error("编辑客户企业标签息出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 创建企业群发
     *
     * @return
     */
    @ApiOperation("创建企业群发")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "JsonStr", value = "JSON参数", required = true, dataType = "String")
    })
    @PostMapping(value = "/addMsgTemplate")
    public Result<String> addMsgTemplate(@RequestBody WxCpMsgTemplate wxCpMsgTemplate, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpMsgTemplateAddResult wxCpMsgTemplateAddResult = contactService.addMsgTemplate(wxCpMsgTemplate);
            return getResult(wxCpMsgTemplateAddResult);
        } catch (WxErrorException e) {
            log.error("添加企业群发消息任务：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }


    /**
     * 获取联系客户统计数据
     *
     * @return
     */
    @ApiOperation("获取联系客户统计数据")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "JsonStr", value = "JSON参数", required = true, dataType = "String")
    })
    @GetMapping(value = "/getUserBehaviorData")
    public Result<WxCpUserExternalUserBehaviorStatistic> getUserBehaviorData(Date startTime, Date endTime, String[] userIds, String[] partyIds, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            WxCpUserExternalUserBehaviorStatistic userBehaviorStatistic = contactService.getUserBehaviorStatistic(startTime, endTime, userIds, partyIds);
            return getResult(userBehaviorStatistic);
        } catch (WxErrorException e) {
            log.error("获取联系客户统计数据：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 发送新客户欢迎语
     *
     * @return
     */
    @ApiOperation("发送新客户欢迎语")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "JsonStr", value = "JSON参数", required = true, dataType = "String")
    })
    @PostMapping(value = "/sendWelcomeMsg")
    public Result<String> sendWelcomeMsg(@RequestBody WxCpWelcomeMsg wxCpWelcomeMsg, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            contactService.sendWelcomeMsg(wxCpWelcomeMsg);
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("发送新客户欢迎语：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

}
